import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { InputNumber, List, Skeleton, message } from 'antd'
import moment from 'moment'
import { MoreOutlined, FileTextOutlined, UserOutlined, BellOutlined, MoneyCollectOutlined } from '@ant-design/icons'
import style from './AcceptDesktop.module.less'
import { computeFee } from '@js/fee_'
import { updateUncompleteMessage } from '@redux/actions'
import { strToNum } from '@src/assets/js/tool'

class AcceptDesktop extends Component {
  state = {
    money: 0,
    acceptanceFee: 0,
    processingFee: 0,
    moneyInputVisible: false,
    yearAcceptNumber: 0,
    yearAcceptNumberLoading: false,
    toExamineNumber: 0,
    toExamineNumberLoading: false,
    // preAcceptNumber: 0,
    // preAcceptNumberLoading: false,
    toFeeNumber: 0,
    toFeeNumberLoading: false,
    sevenDayUnpayNumber: 0,
    sevenDayUnpayNumberLoading: false
  }

  openAcceptCase () {
    this.props.addWindow({ id: 'AcceptCase', title: '收案', componentName: 'AcceptCase' })
  }

  openPreAcceptCase () {
    this.props.addWindow({ id: 'PreAcceptCase', title: '预收案', componentName: 'PreAcceptCase' })
  }

  // 改变争议金额回调
  changeMoney (v) {
    const { processingFee, acceptanceFee } = computeFee(/^\d*$/.test(v) ? v : 0)
    this.setState({
      money: v,
      processingFee,
      acceptanceFee
    })
  }

  // 显示争议金额输入框，并获得焦点
  showMoneyInput () {
    this.setState({
      moneyInputVisible: true,
      money: this.state.money === 0 ? '' : this.state.money
    }, () => {
      if (this.moneyInput) {
        this.moneyInput.focus()
      }
    })
  }

  // 争议金额输入框失去焦点时，隐藏输入框，并限制金额最小为0
  moneyInputBlurHandle () {
    if (!this.state.money || !/^\d*$/.test(this.state.money)) {
      this.setState({
        money: 0
      })
    }
    this.setState({
      moneyInputVisible: false
    })
  }

  // 点击回车键则触发焦点离开事件
  moneyInputEnterHandle () {
    if (this.moneyInput) {
      this.moneyInput.blur()
    }
  }

  // 格式化进去
  formatMoney (value) {
    return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  }

  formatDate (date) {
    if (!date) { return date }
    return moment(date * 1000).format('YYYY-MM-DD HH:mm')
  }

  openMessageList () {
    this.setState({ messageListvisible: false })
    this.props.addWindow({ id: 'MessageList', title: '消息列表', componentName: 'MessageList' })
  }

  // 获取年总收案数
  getYearAcceptNumber () {
    this.setState({ yearAcceptNumberLoading: true })
    const year = moment().year()
    const time = Math.floor(moment(`${year}-01-01`).valueOf() / 1000)
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'accept_datetime', o: '>=', v: time }, { k: 'status', o: 'not in', v: '未提交,已提交' }]),
      conly: true
    }).then(res => {
      this.setState({ yearAcceptNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        yearAcceptNumber: res.data
      })
    }).catch(() => this.setState({ yearAcceptNumberLoading: false }))
  }

  // 获取待审核数
  getToExamineNumber () {
    this.setState({ toExamineNumberLoading: true })
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'submittalid', o: 'not null' }, { k: 'status', o: 'in', v: '待审核' }]),
      conly: true
    }).then(res => {
      this.setState({ toExamineNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        toExamineNumber: res.data
      })
    }).catch(() => this.setState({ toExamineNumberLoading: false }))
  }

  // // 获取预收案数
  // getPreAcceptNumber () {
  //   this.setState({ preAcceptNumberLoading: true })
  //   return this.$get('/api/xapc/case', {
  //     condition: JSON.stringify([{ k: 'status', o: 'in', v: '收案' }, { k: 'cause_action', o: '=', v: '' }]),
  //     conly: true
  //   }).then(res => {
  //     this.setState({ preAcceptNumberLoading: false })
  //     if (res.status !== 1) {
  //       return message.warning(res.message)
  //     }
  //     this.setState({
  //       preAcceptNumber: res.data
  //     })
  //   }).catch(() => this.setState({ preAcceptNumberLoading: false }))
  // }

  // 获取待交费数
  getToFeeNumber () {
    this.setState({ toFeeNumberLoading: true })
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'status', o: 'in', v: '收案' }]),
      conly: true
    }).then(res => {
      this.setState({ toFeeNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        toFeeNumber: res.data
      })
    }).catch(() => this.setState({ toFeeNumberLoading: false }))
  }

  // 获取7天未交费
  getSevenDayUnpayNumber () {
    this.setState({ sevenDayUnpayNumberLoading: true })
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'status', o: 'in', v: '立案' }, { k: 'docket_datetime', o: '<', v: Math.floor(Date.now() / 1000) - 604800 }]),
      conly: true
    }).then(res => {
      this.setState({ sevenDayUnpayNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        sevenDayUnpayNumber: res.data
      })
    }).catch(() => this.setState({ sevenDayUnpayNumberLoading: false }))
  }

  // 获取统计数据
  getStatistics () {
    this.getYearAcceptNumber()
    this.getToExamineNumber()
    // this.getPreAcceptNumber()
    this.getToFeeNumber()
    this.getSevenDayUnpayNumber()
  }

  toDealHandle (d) {
    this.setState({ messageListvisible: false })
    let route = d.route ? d.route : null
    if (!route) {
      return message.warning('处理地址不存在')
    }
    try {
      route = JSON.parse(route)
    } catch (e) {
      return message.warning('获取处理地址错误')
    }
    const component = route.component || route.type
    if (component === 'caseDetail') {
      const { id, operate } = route.meta
      this.props.addWindow({ id: `CaseDetail-${id}`, title: `案件详情-${route.title}`, componentName: 'CaseDetail', forceRefresh: false, meta: { id, operate, editable: true } })
    }
    this.setMessageReaded(d.read_datetime, d.id)
  }

  // 设置未读信息未已读
  setMessageReaded (time, id) {
    if (time) { return false }
    this.$put(`/api/xapc/message/read/${id}`)
      .then(res => {
        if (res.status === 1) {
          this.props.updateUncompleteMessage()
        } else {
          message.warning(res.message)
        }
      })
  }

  gotoYearAccept () {
    const year = moment().year()
    const beginTime = moment(`${year}-01-01`)
    this.props.addWindow({ id: 'AllCaseManage', title: '全委案件', componentName: 'AllCaseManage', forceRefresh: true, meta: { formData: { beginTime, type: 'accept_datetime' } } })
  }

  gotoPreCase () {
    this.props.addWindow({ id: 'AcceptCaseManage', title: '收案案件', componentName: 'AcceptCaseManage', forceRefresh: true, meta: { status: '预收案' } })
  }

  gotoExamine () {
    this.props.addWindow({ id: 'AuditList', title: '待审核', componentName: 'AuditList', forceRefresh: true, meta: { } })
  }

  gotoFee () {
    this.props.addWindow({ id: 'AcceptCaseManage', title: '收案案件', componentName: 'AcceptCaseManage', forceRefresh: true, meta: { status: '待确认交费' } })
  }

  gotoUnpay () {
    this.props.addWindow({ id: 'AcceptCaseManage', title: '立案案件', componentName: 'AcceptCaseManage', forceRefresh: true, meta: { status: '7天未交费' } })
  }

  componentDidMount () {
    this.getStatistics()
  }

  // 渲染争议金额
  renderMoney () {
    if (this.state.moneyInputVisible) {
      return (
        <InputNumber
          ref={ref => { this.moneyInput = ref }} min={0} size='large' value={this.state.money}
          onChange={(...args) => this.changeMoney(...args)}
          maxLength={16}
          onBlur={() => this.moneyInputBlurHandle()}
          onPressEnter={() => this.moneyInputEnterHandle()}
          className={style['body-right-box__input']}
          formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
          parser={value => value.replace(/¥\s?|(,*)/g, '')}
        />
      )
    }
    return (
      <div className={style['body-right-box__money-text']} onClick={() => this.showMoneyInput()}>{`￥${this.state.money || 0}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}</div>
    )
  }

  // 渲染提醒块
  renderNoticeItem (title, numKey, icon, activeStyle, handle = () => {}) {
    if (this.state[`${numKey}Loading`]) {
      return (
        <div className={style['header-block']}>
          <Skeleton active />
        </div>
      )
    }
    const num = this.state[numKey]
    const blockStyle = [style['header-block']]
    if (num > 0) {
      blockStyle.push(activeStyle)
    }
    return (
      <div className={blockStyle.join(' ')} onClick={() => handle()}>
        <div className={style['icon-box']}>
          {icon}
        </div>
        <div className={style['header-block-text']}>
          <div className={style['header-block__text--top']}>{title}</div>
          <div className={style['header-block__text--bottom']}>
            <span className={style['header-block__text-num']}>{num}</span>
            <span className={style['header-block__text-unit']}>件</span>
          </div>
        </div>
      </div>
    )
  }

  // 渲染提示列表
  renderNoticeItemList () {
    return (
      <>
        {this.renderNoticeItem('本年立案数', 'yearAcceptNumber', <FileTextOutlined />, style.active, () => this.gotoYearAccept())}
        {this.renderNoticeItem('待审核', 'toExamineNumber', <UserOutlined />, style.active, () => this.gotoExamine())}
        {/* {this.renderNoticeItem('预收案', 'preAcceptNumber', <FileDoneOutlined />, style.active, () => this.gotoPreCase())} */}
        {this.renderNoticeItem('待确认交费', 'toFeeNumber', <BellOutlined />, style.active, () => this.gotoFee())}
        {this.renderNoticeItem('7天未交费', 'sevenDayUnpayNumber', <MoneyCollectOutlined />, style.active, () => this.gotoUnpay())}
      </>
    )
  }

  // 渲染消息标题
  renderMessageTitle (item, i) {
    return (
      <span className={style['item-name']} onClick={() => this.toDealHandle(item)}>
        <span>{i + 1}、{item.title}</span>
        {item.level ? <span className={style['item-urgency']}>紧急</span> : null}
      </span>
    )
  }

  render () {
    return (
      <div className={style.container}>{/*  */}
        <div className={style.header}>
          <div className={style['header-inner']}>
            {this.renderNoticeItemList()}
          </div>
        </div>
        <div className={style.body}>
          <div className={style['body-left']}>
            <div className={style['body-title-line']}>
              <span className={style['body-title__text']}>提醒通知</span>
              <span className={style['body__more-btn']} onClick={() => this.openMessageList()}>
                <MoreOutlined rotate='90' />
              </span>
            </div>

            <div>
              <List
                itemLayout='horizontal' dataSource={this.props.uncompleteMessageList} pagination={false} renderItem={(item, i) => {
                  return (
                    <List.Item>
                      <Skeleton avatar title={false} loading={item.loading} active>
                        <List.Item.Meta
                          title={this.renderMessageTitle(item, i)}
                          description={item.content}
                        />
                        <span>{this.formatDate(item.create_datetime)}</span>
                      </Skeleton>
                    </List.Item>
                  )
                }}
              />
            </div>
          </div>
          <div className={style['body-right']}>
            <div className={style['body-title-line']}>
              <span className={style['body-title__text']}>仲裁费计算</span>
            </div>
            <div className={style['body-right-box']}>
              <div className={`${style['body-right-box__cell']} ${style['border-bottom-line']}`}>
                <div className={style['fee-line']}>
                  <div className={style['fee-cell']}>
                    <div className={style['fee-cell__title']}>受理费</div>
                    <div className={style['fee-cell__num']}>
                      <span>￥</span><span>{this.formatMoney(this.state.acceptanceFee)}</span>
                    </div>
                  </div>
                  <div className={style['fee-cell']}>
                    <div className={style['fee-cell__title']}>处理费</div>
                    <div className={style['fee-cell__num']}>
                      <span>￥</span><span>{this.formatMoney(this.state.processingFee)}</span>
                    </div>
                  </div>
                  <div className={style['fee-cell']}>
                    <div className={style['fee-cell__title']}>仲裁费</div>
                    <div className={style['fee-cell__num']}>
                      <span>￥</span><span className={style['fee-cell__blue']}>{this.formatMoney(strToNum(this.state.acceptanceFee) + strToNum(this.state.processingFee))}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div className={style['body-right-box__cell']}>
                <div className={style['body-right-box__second-title']}>争议金额</div>
                {this.renderMoney()}
              </div>
            </div>
            {/* <div className={style['body-title-line']}>
              <span className={style['body-title__text']}>快捷操作</span>
            </div>
            <div className={style['body-right-box__btns']}>
              <button onClick={() => this.openAcceptCase()}>收案</button>
              <button onClick={() => this.openPreAcceptCase()}>预收案</button>
            </div> */}
          </div>
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo,
    uncompleteMessageList: state.basic.uncompleteMessageList
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    updateUncompleteMessage: () => dispatch(updateUncompleteMessage(dispatch))
  }
})

export default connect(mapState, mapDispatch)(AcceptDesktop)
